#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
'''
import os
import time
from typing import List

import allure
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait

from src.day36.utils import root_dir
from src.day36.utils.log_util import logger


class BasePage:

    def __init__(self, driver: WebDriver = None):
        if not driver:
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(5)
            self.driver.maximize_window()
        else:
            self.driver = driver

    # def ui_expected(self,func):
    #
    #     def inner(**kwargs):
    #         1. 给要定位的元素进行高亮显示：js脚本来替换这个元素的css属性
    #         2. 异常捕获：在元素获取失败或者说互动失败，pagesource，截图scrrenshot，
    #         将这两个东西存起来，而且放到allure报告里面

    def find(self, by, value=None) -> WebElement:
        """
        封装查找
        :param by:
        :param value:
        :return:
        """
        try:
            if isinstance(by, tuple):
                logger.debug(f"使用 {by[0]} 的定位方式,进行元素 {by[1]} 的定位")
                ele = self.driver.find_element(*by)
            else:
                logger.debug(f"使用 {by} 的定位方式,进行元素 {value} 的定位")
                ele = self.driver.find_element(by, value)
            try:
                # 上色
                self.mark_element(ele)
            except Exception as e:
                pass
            return ele
        except Exception as e:
            self.save_screen_shot()
            self.save_page_source()
            raise e
    def mark_element(self, element: WebElement):
        """
        元素上色，加边框
        :return:
        """
        self.driver.execute_script("arguments[0].style.border = '2px solid red';", element)
        self.save_screen_shot()
        time.sleep(0.2)
        self.driver.execute_script("arguments[0].style.border = '';", element)

    def get_time_name(self, dir_name, file_name):

        dir_path = f"{root_dir}/data/{dir_name}"
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        return f'{dir_path}/{file_name}'

    def save_page_source(self):
        time_format = time.strftime('%m-%d-%H-%M-%S')
        html_data = self.driver.page_source
        path = self.get_time_name('page_source', f'PageSource{time_format}.html')
        with open(path, "w", encoding="utf-8") as f:
            f.write(html_data)
        allure.attach.file(path, attachment_type=allure.attachment_type.HTML)

    def save_screen_shot(self):
        time_format = time.strftime('%m-%d-%H-%M-%S')
        path = self.get_time_name('screen_shot', f'img{time_format}.png')
        self.driver.save_screenshot(path)
        allure.attach.file(path, attachment_type=allure.attachment_type.PNG)

    def finds(self, by, value=None) -> List[WebElement]:
        """
        封装查找多个
        :param by:
        :param value:
        :return:
        """
        if isinstance(by, tuple):
            logger.debug(f"使用 {by[0]} 的定位方式,进行元素 {by[1]} 的定位")
            eles = self.driver.find_elements(*by)
        else:
            logger.debug(f"使用 {by} 的定位方式,进行元素 {value} 的定位")
            eles = self.driver.find_elements(by, value)
        return eles

    def find_and_click(self, by, value=None):
        """
        查找并点击
        :param by:
        :param value:
        :return:
        """
        ele = self.find(by=by, value=value)
        ele.click()

    def find_and_send(self, by, value=None, text=None):
        """
        查找并输入
        :param by:
        :param value:
        :param text:
        :return:
        """

        ele = self.find(by=by, value=value)
        logger.debug(f"进行信息{text}的输入操作")
        ele.send_keys(text)

    def wait(self, method, time_out=5):
        el = WebDriverWait(self.driver, time_out).until(method)
        return el
